package com.yituo.mjworld.mvc.action.admin;

import com.yituo.mjworld.core.annotation.Check;
import com.yituo.mjworld.core.exception.MyException;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.action.IBaseAction;
import com.yituo.mjworld.mvc.entity.web.WebBanner;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.service.impl.BannerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * 轮播图的Action
 */
@Component
public class BannerAction implements IBaseAction {

  @Autowired
  BannerServiceImpl bannerService;

  /**
   * 超级管理员可以查询
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Check(form = QueryForm.class)
  @Override
  public void getList(MyHttpRequest req, MyHttpResponse res) throws IOException {
    QueryForm form = (QueryForm) req.getForm();
    res.success(this.bannerService.getList(form));
  }

  @Override
  @Check(form = DeleteForm.class)
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {
    DeleteForm form = (DeleteForm) req.getForm();
    res.setResult(this.bannerService.delete(form));
  }

  /**
   * 保存和更新接口
   *
   * @param req
   * @param res
   * @throws IOException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  @Override
  @Check(form = WebBanner.class)
  public void saveOrUpdate(MyHttpRequest req, MyHttpResponse res) throws IOException, InvocationTargetException, IllegalAccessException {
    WebBanner form = (WebBanner) req.getForm();
    res.setResult(this.bannerService.saveOrUpdate(form));
  }


  /**
   * 更新图片的URL
   * <p>
   * 前端校验不会传空URL.且会删除之前的图片项.
   * <p>
   * 但是该接口处理空URL,时,仍会删除旧图片.
   *
   * @param req
   * @param res
   * @throws IOException
   */
  public void updateUrl(MyHttpRequest req, MyHttpResponse res) throws IOException {
    int id = 0;
    String imgUrl = null;
    try {
      id = Integer.parseInt(req.getParameter("id"));
      imgUrl = req.getParameter("imgUrl");
      if (id < 0) {
        throw new MyException("二级分类ID不存在!");
      }
      if (StringUtils.isEmpty(imgUrl)) {
        imgUrl = "";
      }
    } catch (Exception e) {
      res.failedFor302("参数错误!");
    }
    res.setResult(bannerService.updateUrl(id, imgUrl));
  }
}
